package thread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Author: Miyako
 * @Date: 2024-07-22-12:45
 * @Description: 群聊版客户端
 */
public class TClient {
    private Socket socket;
    private String name;
    void Link(){//连接服务器
        try{
            System.out.println("Server Link....");
            socket = new Socket("127.0.0.1",8888);
            System.out.println("Server Link success");
        }catch (IOException e){
            e.printStackTrace();
            System.out.println("Server Link defeat");
        }

    }
    void  doStart(){//完成接收和发送功能
        Scanner sc = new Scanner(System.in);
        String str ;
        PrintWriter pw = null;
        try{
             pw=new PrintWriter( socket.getOutputStream(),true);
             while (true) {//循环输入昵称,直到输入昵称合规
                 System.out.println("输入您的昵称");
                 name = sc.next();
                 if (name.trim().isEmpty()){
                     System.out.println("昵称不能为空");
                     continue;
                 }
                 pw.println(name);//发送昵称
                 break;
             }
            new Thread(new ServerHander()).start();//新建一个线程去接收数据
            while(true){
                System.out.print("输入聊天信息:>");
                str = sc.next();
                if ("exit".equalsIgnoreCase(str))break;
                pw.println(str);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            sc.close();
            if (pw==null) pw.close();
        }

    }
    class ServerHander implements Runnable{//接收过滤并打印信息
        @Override
        public void run() {
            BufferedReader br = null;
            String s;
            try{
                br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while ((s=br.readLine())!=null){
//                    if (!s.startsWith(name))//过滤掉自己的信息
                        System.out.print("\n"+s);
                }
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                try{
                    if(br==null) br.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }


    public static void main(String[] args) {
       TClient tc1 =  new TClient();
       tc1.Link();
       tc1.doStart();

    }
}
